package com.hxl.linuxfilemanager.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxl.linuxfilemanager.anno.ExcludeInterceptor;
import com.hxl.linuxfilemanager.config.LinuxPropertiesConfig;
import com.hxl.linuxfilemanager.entity.R;
import com.hxl.linuxfilemanager.exceptions.SysException;
import com.hxl.linuxfilemanager.service.impl.UserServiceImpl;
import com.hxl.linuxfilemanager.util.ResponseUtils;
import com.hxl.linuxfilemanager.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 身份拦截器，如果是页面，则重定向的登录页面，如果是AJAX，则提示错误
 */
public class AuthorInterceptors implements HandlerInterceptor {
    @Autowired
    LinuxPropertiesConfig linuxPropertiesConfig;

    @Autowired
    UserServiceImpl userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            ExcludeInterceptor methodAnnotation = handlerMethod.getMethodAnnotation(ExcludeInterceptor.class);
            if (methodAnnotation!=null){
                return true;
            }
        }
        /**
         * 判断是否登录
         */
        Object login =  request.getSession().getAttribute("login");
        if(login==null || ( ((boolean)login)==false)){
            R<String> result = ResponseUtils.error(-200, "未登录");
            byte[] bytes = new ObjectMapper().writeValueAsBytes(result);
            response.setHeader("content-type", "application/json;charset=utf-8");
            response.getOutputStream().write(bytes);
            return false;
        }

        return true;
    }
}
